﻿using Qiniu.Http;
using Qiniu.IO;
using Qiniu.IO.Model;
using Qiniu.Util;
using Microsoft.OpenApi.Writers;

namespace RabitPart.ReadApi
{
    public class QiniuUtils
    {
        private readonly IConfiguration _configuration;
        public QiniuUtils(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 上传文件到七牛云
        /// </summary>
        /// <param name="data">要上产的文件数据</param>
        /// <param name="saveKey">文件在七牛云中的保存名称</param>
        public void UploadFile(byte[] data, string saveKey)
        {
            //校验输入参数
            if (data == null || data.Length == 0)
            {
                throw new ArgumentException("上传数据不能为空",nameof(data));
            }
            if (string.IsNullOrEmpty(saveKey))
            {
                throw new ArgumentException("保存的文件名称不能为空",nameof(saveKey));
            }

            //从配置中获取AccessKey 和 SecreKey
            var accessKey = _configuration["Qiniu:AccessKey"];
            var secretKey = _configuration["Qiniu:SecretKey"];
            if(string.IsNullOrWhiteSpace(accessKey) || string.IsNullOrWhiteSpace(secretKey))
            {
                throw new InvalidOperationException("七牛云的AccessKey 或 SecretKey 未配置");
            }

            string bucket = "alnn";

            //创建上传策略
            PutPolicy putPolicy = new PutPolicy
            {
                Scope = bucket,
            };
            //配置上传凭证有效期（实例2小时，可调整）
            putPolicy.SetExpires(3600);

            //自动选择区域
            Qiniu.Common.Config.AutoZone(accessKey, bucket, false);

            //生成上传凭证
            string jstr = putPolicy.ToJsonString();
            string token = Auth.CreateUploadToken(new Mac(accessKey, secretKey), jstr);
            UploadManager um = new UploadManager();

            //上传数据
            HttpResult result = um.UploadData(data, saveKey, token);
            if (result.Code == 200)
            {
                Console.WriteLine("上传成功: " + result.Text);
            }
            else
            {
                Console.WriteLine("上传失败: " + result.Text);
                throw new Exception($"上传失败，状态码: {result.Code}, 错误信息: {result.Text}");
            }


        }


    }
}
